{
 "nbformat_minor": 0, 
 "nbformat": 4, 
 "cells": [
  {
   "source": [
    "# Multiclass Support Vector Machine exercise\n", 
    "\n", 
    "*Complete and hand in this completed worksheet (including its outputs and any supporting code outside of the worksheet) with your assignment submission. For more details see the [assignments page](http://vision.stanford.edu/teaching/cs231n/assignments.html) on the course website.*\n", 
    "\n", 
    "In this exercise you will:\n", 
    "    \n", 
    "- implement a fully-vectorized **loss function** for the SVM\n", 
    "- implement the fully-vectorized expression for its **analytic gradient**\n", 
    "- **check your implementation** using numerical gradient\n", 
    "- use a validation set to **tune the learning rate and regularization** strength\n", 
    "- **optimize** the loss function with **SGD**\n", 
    "- **visualize** the final learned weights\n"
   ], 
   "cell_type": "markdown", 
   "metadata": {}
  }, 
  {
   "execution_count": null, 
   "cell_type": "code", 
   "source": [
    "# Run some setup code for this notebook.\n", 
    "\n", 
    "import random\n", 
    "import numpy as np\n", 
    "from cs231n.data_utils import load_CIFAR10\n", 
    "import matplotlib.pyplot as plt\n", 
    "\n", 
    "from __future__ import print_function\n", 
    "\n", 
    "# This is a bit of magic to make matplotlib figures appear inline in the\n", 
    "# notebook rather than in a new window.\n", 
    "%matplotlib inline\n", 
    "plt.rcParams['figure.figsize'] = (10.0, 8.0) # set default size of plots\n", 
    "plt.rcParams['image.interpolation'] = 'nearest'\n", 
    "plt.rcParams['image.cmap'] = 'gray'\n", 
    "\n", 
    "# Some more magic so that the notebook will reload external python modules;\n", 
    "# see http://stackoverflow.com/questions/1907993/autoreload-of-modules-in-ipython\n", 
    "%load_ext autoreload\n", 
    "%autoreload 2"
   ], 
   "outputs": [], 
   "metadata": {
    "collapsed": false
   }
  }, 
  {
   "source": [
    "## CIFAR-10 Data Loading and Preprocessing"
   ], 
   "cell_type": "markdown", 
   "metadata": {}
  }, 
  {
   "execution_count": null, 
   "cell_type": "code", 
   "source": [
    "# Load the raw CIFAR-10 data.\n", 
    "cifar10_dir = 'cs231n/datasets/cifar-10-batches-py'\n", 
    "X_train, y_train, X_test, y_test = load_CIFAR10(cifar10_dir)\n", 
    "\n", 
    "# As a sanity check, we print out the size of the training and test data.\n", 
    "print('Training data shape: ', X_train.shape)\n", 
    "print('Training labels shape: ', y_train.shape)\n", 
    "print('Test data shape: ', X_test.shape)\n", 
    "print('Test labels shape: ', y_test.shape)"
   ], 
   "outputs": [], 
   "metadata": {
    "collapsed": false
   }
  }, 
  {
   "execution_count": null, 
   "cell_type": "code", 
   "source": [
    "# Visualize some examples from the dataset.\n", 
    "# We show a few examples of training images from each class.\n", 
    "classes = ['plane', 'car', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck']\n", 
    "num_classes = len(classes)\n", 
    "samples_per_class = 7\n", 
    "for y, cls in enumerate(classes):\n", 
    "    idxs = np.flatnonzero(y_train == y)\n", 
    "    idxs = np.random.choice(idxs, samples_per_class, replace=False)\n", 
    "    for i, idx in enumerate(idxs):\n", 
    "        plt_idx = i * num_classes + y + 1\n", 
    "        plt.subplot(samples_per_class, num_classes, plt_idx)\n", 
    "        plt.imshow(X_train[idx].astype('uint8'))\n", 
    "        plt.axis('off')\n", 
    "        if i == 0:\n", 
    "            plt.title(cls)\n", 
    "plt.show()"
   ], 
   "outputs": [], 
   "metadata": {
    "collapsed": false
   }
  }, 
  {
   "execution_count": null, 
   "cell_type": "code", 
   "source": [
    "# Split the data into train, val, and test sets. In addition we will\n", 
    "# create a small development set as a subset of the training data;\n", 
    "# we can use this for development so our code runs faster.\n", 
    "num_training = 49000\n", 
    "num_validation = 1000\n", 
    "num_test = 1000\n", 
    "num_dev = 500\n", 
    "\n", 
    "# Our validation set will be num_validation points from the original\n", 
    "# training set.\n", 
    "mask = range(num_training, num_training + num_validation)\n", 
    "X_val = X_train[mask]\n", 
    "y_val = y_train[mask]\n", 
    "\n", 
    "# Our training set will be the first num_train points from the original\n", 
    "# training set.\n", 
    "mask = range(num_training)\n", 
    "X_train = X_train[mask]\n", 
    "y_train = y_train[mask]\n", 
    "\n", 
    "# We will also make a development set, which is a small subset of\n", 
    "# the training set.\n", 
    "mask = np.random.choice(num_training, num_dev, replace=False)\n", 
    "X_dev = X_train[mask]\n", 
    "y_dev = y_train[mask]\n", 
    "\n", 
    "# We use the first num_test points of the original test set as our\n", 
    "# test set.\n", 
    "mask = range(num_test)\n", 
    "X_test = X_test[mask]\n", 
    "y_test = y_test[mask]\n", 
    "\n", 
    "print('Train data shape: ', X_train.shape)\n", 
    "print('Train labels shape: ', y_train.shape)\n", 
    "print('Validation data shape: ', X_val.shape)\n", 
    "print('Validation labels shape: ', y_val.shape)\n", 
    "print('Test data shape: ', X_test.shape)\n", 
    "print('Test labels shape: ', y_test.shape)"
   ], 
   "outputs": [], 
   "metadata": {
    "collapsed": false
   }
  }, 
  {
   "execution_count": null, 
   "cell_type": "code", 
   "source": [
    "# Preprocessing: reshape the image data into rows\n", 
    "X_train = np.reshape(X_train, (X_train.shape[0], -1))\n", 
    "X_val = np.reshape(X_val, (X_val.shape[0], -1))\n", 
    "X_test = np.reshape(X_test, (X_test.shape[0], -1))\n", 
    "X_dev = np.reshape(X_dev, (X_dev.shape[0], -1))\n", 
    "\n", 
    "# As a sanity check, print out the shapes of the data\n", 
    "print('Training data shape: ', X_train.shape)\n", 
    "print('Validation data shape: ', X_val.shape)\n", 
    "print('Test data shape: ', X_test.shape)\n", 
    "print('dev data shape: ', X_dev.shape)"
   ], 
   "outputs": [], 
   "metadata": {
    "collapsed": false
   }
  }, 
  {
   "execution_count": null, 
   "cell_type": "code", 
   "source": [
    "# Preprocessing: subtract the mean image\n", 
    "# first: compute the image mean based on the training data\n", 
    "mean_image = np.mean(X_train, axis=0)\n", 
    "print(mean_image[:10]) # print a few of the elements\n", 
    "plt.figure(figsize=(4,4))\n", 
    "plt.imshow(mean_image.reshape((32,32,3)).astype('uint8')) # visualize the mean image\n", 
    "plt.show()"
   ], 
   "outputs": [], 
   "metadata": {
    "collapsed": false
   }
  }, 
  {
   "execution_count": null, 
   "cell_type": "code", 
   "source": [
    "# second: subtract the mean image from train and test data\n", 
    "X_train -= mean_image\n", 
    "X_val -= mean_image\n", 
    "X_test -= mean_image\n", 
    "X_dev -= mean_image"
   ], 
   "outputs": [], 
   "metadata": {
    "collapsed": false
   }
  }, 
  {
   "execution_count": null, 
   "cell_type": "code", 
   "source": [
    "# third: append the bias dimension of ones (i.e. bias trick) so that our SVM\n", 
    "# only has to worry about optimizing a single weight matrix W.\n", 
    "X_train = np.hstack([X_train, np.ones((X_train.shape[0], 1))])\n", 
    "X_val = np.hstack([X_val, np.ones((X_val.shape[0], 1))])\n", 
    "X_test = np.hstack([X_test, np.ones((X_test.shape[0], 1))])\n", 
    "X_dev = np.hstack([X_dev, np.ones((X_dev.shape[0], 1))])\n", 
    "\n", 
    "print(X_train.shape, X_val.shape, X_test.shape, X_dev.shape)"
   ], 
   "outputs": [], 
   "metadata": {
    "collapsed": false
   }
  }, 
  {
   "source": [
    "## SVM Classifier\n", 
    "\n", 
    "Your code for this section will all be written inside **cs231n/classifiers/linear_svm.py**. \n", 
    "\n", 
    "As you can see, we have prefilled the function `compute_loss_naive` which uses for loops to evaluate the multiclass SVM loss function. "
   ], 
   "cell_type": "markdown", 
   "metadata": {}
  }, 
  {
   "execution_count": null, 
   "cell_type": "code", 
   "source": [
    "# Evaluate the naive implementation of the loss we provided for you:\n", 
    "from cs231n.classifiers.linear_svm import svm_loss_naive\n", 
    "import time\n", 
    "\n", 
    "# generate a random SVM weight matrix of small numbers\n", 
    "W = np.random.randn(3073, 10) * 0.0001 \n", 
    "\n", 
    "loss, grad = svm_loss_naive(W, X_dev, y_dev, 0.000005)\n", 
    "print('loss: %f' % (loss, ))"
   ], 
   "outputs": [], 
   "metadata": {
    "collapsed": false
   }
  }, 
  {
   "source": [
    "The `grad` returned from the function above is right now all zero. Derive and implement the gradient for the SVM cost function and implement it inline inside the function `svm_loss_naive`. You will find it helpful to interleave your new code inside the existing function.\n", 
    "\n", 
    "To check that you have correctly implemented the gradient correctly, you can numerically estimate the gradient of the loss function and compare the numeric estimate to the gradient that you computed. We have provided code that does this for you:"
   ], 
   "cell_type": "markdown", 
   "metadata": {}
  }, 
  {
   "execution_count": null, 
   "cell_type": "code", 
   "source": [
    "# Once you've implemented the gradient, recompute it with the code below\n", 
    "# and gradient check it with the function we provided for you\n", 
    "\n", 
    "# Compute the loss and its gradient at W.\n", 
    "loss, grad = svm_loss_naive(W, X_dev, y_dev, 0.0)\n", 
    "\n", 
    "# Numerically compute the gradient along several randomly chosen dimensions, and\n", 
    "# compare them with your analytically computed gradient. The numbers should match\n", 
    "# almost exactly along all dimensions.\n", 
    "from cs231n.gradient_check import grad_check_sparse\n", 
    "f = lambda w: svm_loss_naive(w, X_dev, y_dev, 0.0)[0]\n", 
    "grad_numerical = grad_check_sparse(f, W, grad)\n", 
    "\n", 
    "# do the gradient check once again with regularization turned on\n", 
    "# you didn't forget the regularization gradient did you?\n", 
    "loss, grad = svm_loss_naive(W, X_dev, y_dev, 5e1)\n", 
    "f = lambda w: svm_loss_naive(w, X_dev, y_dev, 5e1)[0]\n", 
    "grad_numerical = grad_check_sparse(f, W, grad)"
   ], 
   "outputs": [], 
   "metadata": {
    "collapsed": false
   }
  }, 
  {
   "source": [
    "### Inline Question 1:\n", 
    "It is possible that once in a while a dimension in the gradcheck will not match exactly. What could such a discrepancy be caused by? Is it a reason for concern? What is a simple example in one dimension where a gradient check could fail? *Hint: the SVM loss function is not strictly speaking differentiable*\n", 
    "\n", 
    "**Your Answer:** *fill this in.*"
   ], 
   "cell_type": "markdown", 
   "metadata": {}
  }, 
  {
   "execution_count": null, 
   "cell_type": "code", 
   "source": [
    "# Next implement the function svm_loss_vectorized; for now only compute the loss;\n", 
    "# we will implement the gradient in a moment.\n", 
    "tic = time.time()\n", 
    "loss_naive, grad_naive = svm_loss_naive(W, X_dev, y_dev, 0.000005)\n", 
    "toc = time.time()\n", 
    "print('Naive loss: %e computed in %fs' % (loss_naive, toc - tic))\n", 
    "\n", 
    "from cs231n.classifiers.linear_svm import svm_loss_vectorized\n", 
    "tic = time.time()\n", 
    "loss_vectorized, _ = svm_loss_vectorized(W, X_dev, y_dev, 0.000005)\n", 
    "toc = time.time()\n", 
    "print('Vectorized loss: %e computed in %fs' % (loss_vectorized, toc - tic))\n", 
    "\n", 
    "# The losses should match but your vectorized implementation should be much faster.\n", 
    "print('difference: %f' % (loss_naive - loss_vectorized))"
   ], 
   "outputs": [], 
   "metadata": {
    "collapsed": false
   }
  }, 
  {
   "execution_count": null, 
   "cell_type": "code", 
   "source": [
    "# Complete the implementation of svm_loss_vectorized, and compute the gradient\n", 
    "# of the loss function in a vectorized way.\n", 
    "\n", 
    "# The naive implementation and the vectorized implementation should match, but\n", 
    "# the vectorized version should still be much faster.\n", 
    "tic = time.time()\n", 
    "_, grad_naive = svm_loss_naive(W, X_dev, y_dev, 0.000005)\n", 
    "toc = time.time()\n", 
    "print('Naive loss and gradient: computed in %fs' % (toc - tic))\n", 
    "\n", 
    "tic = time.time()\n", 
    "_, grad_vectorized = svm_loss_vectorized(W, X_dev, y_dev, 0.000005)\n", 
    "toc = time.time()\n", 
    "print('Vectorized loss and gradient: computed in %fs' % (toc - tic))\n", 
    "\n", 
    "# The loss is a single number, so it is easy to compare the values computed\n", 
    "# by the two implementations. The gradient on the other hand is a matrix, so\n", 
    "# we use the Frobenius norm to compare them.\n", 
    "difference = np.linalg.norm(grad_naive - grad_vectorized, ord='fro')\n", 
    "print('difference: %f' % difference)"
   ], 
   "outputs": [], 
   "metadata": {
    "collapsed": false
   }
  }, 
  {
   "source": [
    "### Stochastic Gradient Descent\n", 
    "\n", 
    "We now have vectorized and efficient expressions for the loss, the gradient and our gradient matches the numerical gradient. We are therefore ready to do SGD to minimize the loss."
   ], 
   "cell_type": "markdown", 
   "metadata": {}
  }, 
  {
   "execution_count": null, 
   "cell_type": "code", 
   "source": [
    "# In the file linear_classifier.py, implement SGD in the function\n", 
    "# LinearClassifier.train() and then run it with the code below.\n", 
    "from cs231n.classifiers import LinearSVM\n", 
    "svm = LinearSVM()\n", 
    "tic = time.time()\n", 
    "loss_hist = svm.train(X_train, y_train, learning_rate=1e-7, reg=2.5e4,\n", 
    "                      num_iters=1500, verbose=True)\n", 
    "toc = time.time()\n", 
    "print('That took %fs' % (toc - tic))"
   ], 
   "outputs": [], 
   "metadata": {
    "collapsed": false
   }
  }, 
  {
   "execution_count": null, 
   "cell_type": "code", 
   "source": [
    "# A useful debugging strategy is to plot the loss as a function of\n", 
    "# iteration number:\n", 
    "plt.plot(loss_hist)\n", 
    "plt.xlabel('Iteration number')\n", 
    "plt.ylabel('Loss value')\n", 
    "plt.show()"
   ], 
   "outputs": [], 
   "metadata": {
    "collapsed": false
   }
  }, 
  {
   "execution_count": null, 
   "cell_type": "code", 
   "source": [
    "# Write the LinearSVM.predict function and evaluate the performance on both the\n", 
    "# training and validation set\n", 
    "y_train_pred = svm.predict(X_train)\n", 
    "print('training accuracy: %f' % (np.mean(y_train == y_train_pred), ))\n", 
    "y_val_pred = svm.predict(X_val)\n", 
    "print('validation accuracy: %f' % (np.mean(y_val == y_val_pred), ))"
   ], 
   "outputs": [], 
   "metadata": {
    "collapsed": false
   }
  }, 
  {
   "execution_count": null, 
   "cell_type": "code", 
   "source": [
    "# Use the validation set to tune hyperparameters (regularization strength and\n", 
    "# learning rate). You should experiment with different ranges for the learning\n", 
    "# rates and regularization strengths; if you are careful you should be able to\n", 
    "# get a classification accuracy of about 0.4 on the validation set.\n", 
    "learning_rates = [1e-7, 5e-5]\n", 
    "regularization_strengths = [2.5e4, 5e4]\n", 
    "\n", 
    "# results is dictionary mapping tuples of the form\n", 
    "# (learning_rate, regularization_strength) to tuples of the form\n", 
    "# (training_accuracy, validation_accuracy). The accuracy is simply the fraction\n", 
    "# of data points that are correctly classified.\n", 
    "results = {}\n", 
    "best_val = -1   # The highest validation accuracy that we have seen so far.\n", 
    "best_svm = None # The LinearSVM object that achieved the highest validation rate.\n", 
    "\n", 
    "################################################################################\n", 
    "# TODO:                                                                        #\n", 
    "# Write code that chooses the best hyperparameters by tuning on the validation #\n", 
    "# set. For each combination of hyperparameters, train a linear SVM on the      #\n", 
    "# training set, compute its accuracy on the training and validation sets, and  #\n", 
    "# store these numbers in the results dictionary. In addition, store the best   #\n", 
    "# validation accuracy in best_val and the LinearSVM object that achieves this  #\n", 
    "# accuracy in best_svm.                                                        #\n", 
    "#                                                                              #\n", 
    "# Hint: You should use a small value for num_iters as you develop your         #\n", 
    "# validation code so that the SVMs don't take much time to train; once you are #\n", 
    "# confident that your validation code works, you should rerun the validation   #\n", 
    "# code with a larger value for num_iters.                                      #\n", 
    "################################################################################\n", 
    "pass\n", 
    "################################################################################\n", 
    "#                              END OF YOUR CODE                                #\n", 
    "################################################################################\n", 
    "    \n", 
    "# Print out results.\n", 
    "for lr, reg in sorted(results):\n", 
    "    train_accuracy, val_accuracy = results[(lr, reg)]\n", 
    "    print('lr %e reg %e train accuracy: %f val accuracy: %f' % (\n", 
    "                lr, reg, train_accuracy, val_accuracy))\n", 
    "    \n", 
    "print('best validation accuracy achieved during cross-validation: %f' % best_val)"
   ], 
   "outputs": [], 
   "metadata": {
    "collapsed": false
   }
  }, 
  {
   "execution_count": null, 
   "cell_type": "code", 
   "source": [
    "# Visualize the cross-validation results\n", 
    "import math\n", 
    "x_scatter = [math.log10(x[0]) for x in results]\n", 
    "y_scatter = [math.log10(x[1]) for x in results]\n", 
    "\n", 
    "# plot training accuracy\n", 
    "marker_size = 100\n", 
    "colors = [results[x][0] for x in results]\n", 
    "plt.subplot(2, 1, 1)\n", 
    "plt.scatter(x_scatter, y_scatter, marker_size, c=colors)\n", 
    "plt.colorbar()\n", 
    "plt.xlabel('log learning rate')\n", 
    "plt.ylabel('log regularization strength')\n", 
    "plt.title('CIFAR-10 training accuracy')\n", 
    "\n", 
    "# plot validation accuracy\n", 
    "colors = [results[x][1] for x in results] # default size of markers is 20\n", 
    "plt.subplot(2, 1, 2)\n", 
    "plt.scatter(x_scatter, y_scatter, marker_size, c=colors)\n", 
    "plt.colorbar()\n", 
    "plt.xlabel('log learning rate')\n", 
    "plt.ylabel('log regularization strength')\n", 
    "plt.title('CIFAR-10 validation accuracy')\n", 
    "plt.show()"
   ], 
   "outputs": [], 
   "metadata": {
    "collapsed": false
   }
  }, 
  {
   "execution_count": null, 
   "cell_type": "code", 
   "source": [
    "# Evaluate the best svm on test set\n", 
    "y_test_pred = best_svm.predict(X_test)\n", 
    "test_accuracy = np.mean(y_test == y_test_pred)\n", 
    "print('linear SVM on raw pixels final test set accuracy: %f' % test_accuracy)"
   ], 
   "outputs": [], 
   "metadata": {
    "collapsed": false
   }
  }, 
  {
   "execution_count": null, 
   "cell_type": "code", 
   "source": [
    "# Visualize the learned weights for each class.\n", 
    "# Depending on your choice of learning rate and regularization strength, these may\n", 
    "# or may not be nice to look at.\n", 
    "w = best_svm.W[:-1,:] # strip out the bias\n", 
    "w = w.reshape(32, 32, 3, 10)\n", 
    "w_min, w_max = np.min(w), np.max(w)\n", 
    "classes = ['plane', 'car', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck']\n", 
    "for i in range(10):\n", 
    "    plt.subplot(2, 5, i + 1)\n", 
    "      \n", 
    "    # Rescale the weights to be between 0 and 255\n", 
    "    wimg = 255.0 * (w[:, :, :, i].squeeze() - w_min) / (w_max - w_min)\n", 
    "    plt.imshow(wimg.astype('uint8'))\n", 
    "    plt.axis('off')\n", 
    "    plt.title(classes[i])"
   ], 
   "outputs": [], 
   "metadata": {
    "collapsed": false
   }
  }, 
  {
   "source": [
    "### Inline question 2:\n", 
    "Describe what your visualized SVM weights look like, and offer a brief explanation for why they look they way that they do.\n", 
    "\n", 
    "**Your answer:** *fill this in*"
   ], 
   "cell_type": "markdown", 
   "metadata": {}
  }
 ], 
 "metadata": {
  "kernelspec": {
   "display_name": "Python 2", 
   "name": "python2", 
   "language": "python"
  }, 
  "language_info": {
   "mimetype": "text/x-python", 
   "nbconvert_exporter": "python", 
   "name": "python", 
   "file_extension": ".py", 
   "version": "2.7.6", 
   "pygments_lexer": "ipython2", 
   "codemirror_mode": {
    "version": 2, 
    "name": "ipython"
   }
  }
 }
}